<?php

require_once 'SmartL/Zend/Controller/Action.php';
require_once 'Db/Shop/Record/BasketItem.php';
require_once 'Db/Shop/Record/Product.php';
require_once 'Db/Shop/Record/Category.php';

class UserBasketController extends SmartL_Zend_Controller_Action
{
    /**
     * List of user's basket items.
     * Parameters: *user
     */
    public function itemsListAction ()
    {
        $user = Zend_Auth::getInstance()->getIdentity();
        if (empty($user)) {
            $this->_helper->redirector->goto("index", "index");
        }
        $query = new Doctrine_Query();
        $basketItems = $query->select("b.productId, b.userId, p.price, t.name")->from("Db_Shop_Record_BasketItem b")->leftJoin("b.Product p")->leftJoin("p.Translation t")->where("b.userId = ?", array($user->id))->orderBy("t.name ASC")->execute();
        $this->view->basketItems = $basketItems;
        $this->view->totalPrice = 0;
        foreach ($this->view->basketItems as $item) {
            $itemTotalPrice = $item->Product->price * $item->amount;
            $item->mapValue('price', $itemTotalPrice);
            $this->view->totalPrice += $itemTotalPrice;
        }
        
        if ($this->_getParam('invalid', 0) == 1) {
        	$this->view->isValid = false;
        }
    }
    /**
     * Add item to basket.
     *
     * @param Db_Shop_Record_User $user
     * @param integer $productId
     * @param integer $ammount
     */
    private function _addBasketItem ($userId, $productId, $amount)
    {
        $basketItem = new Db_Shop_Record_BasketItem();
        $basketItem->userId = $userId;
        $basketItem->amount = $amount;
        $basketItem->productId = $productId;
        $basketItem->save();
    }
    /**
     * Add item to basket.
     * Parameters: 
     *    id - id of product
     *    amount - (optional) amount of products.
     *    *user
     *
     */
    public function addBasketItemAction ()
    {
        $user = Zend_Auth::getInstance()->getIdentity();
        
        if (empty($user)) {
            $this->_helper->redirector->goto("index", "index");
        }
        if ($this->_hasParam('id')) {
            $query = new Doctrine_Query();
            $basketItem = $query->select('i.amount')
                                ->from('Db_Shop_Record_BasketItem i')
                                ->where('userId = ? and productId = ?', 
                                    array($user->id, $this->_getParam('id')))
                                ->execute()->getFirst();

            if (empty($basketItem)) {
                $this->_addBasketItem($user->id, $this->_getParam('id'), $this->_hasParam('amount') ? $this->_getParam("amount") : 1);
            }
            else {
                $this->_updateBasketItem($user, $this->_getParam('id'), $basketItem->amount+1);
            }
        }
        $this->_helper->redirector->goto('items-list', 'user-basket');
    }
    /**
     * Remove item from basket.
     *
     * @param Db_Shop_Record_User $user
     * @param integer $productId
     */
    private function _removeBasketItem (Doctrine_Record $user, $productId)
    {
        $query = new Doctrine_Query();
        $query->delete()->from('Db_Shop_Record_BasketItem i')->where('i.userId = ? AND i.productId =?', array($user->id , $productId))->execute();
    }
    /**
     * Remove item from basket.
     * Parameters: item id, *user      
     */
    public function removeBasketItemAction ()
    {
        $user = Zend_Auth::getInstance()->getIdentity();
        if (empty($user)) {
            $this->_helper->redirector->goto("index", "index");
        }
        if ($user and $this->_hasParam('id')) {
            $this->removeBasketItem($user, $this->_getParam('id'));
        }
    }
    /**
     * Update basket item in db. 
     *
     * @param Db_Shop_Record_User $user
     * @param integer $productId
     * @param integer $amount
     */
    private function _updateBasketItem (Doctrine_Record $user, $productId, $amount)
    {
        if ($amount <= 0) {
            return $this->_removeBasketItem($user, $productId);
        }
        $query = new Doctrine_Query();
        $query->update('Db_Shop_Record_BasketItem i')->set('i.amount', $amount)->where('i.userId = ? and i.productId = ?', array($user->id , $productId))->execute();
    }
    /**
     * Update basket items amount.
     * parameters: 
     *    amount_%id% - new amount of products.
     *    *user
     */
    public function updateBasketItemsAction ()
    {
        $user = Zend_Auth::getInstance()->getIdentity();
        if (empty($user)) {
            $this->_helper->redirector->goto("index", "index");
        }
        $query = new Doctrine_Query();
        $basketItems = $query->select("b.productId, b.amount")->from("Db_Shop_Record_BasketItem b")->where("b.userId = ?", array($user->id))->execute();
        foreach ($basketItems as $item) {
            if ($user instanceof Doctrine_Record && $this->_hasParam('amount_' . $item->productId)) {
                $amount = ($this->_getParam('amount_' . $item->productId));
                if (is_numeric($amount) === false) {
					$this->_helper->redirector->goto('items-list', 'user-basket', null, array('invalid' => '1'));
                	return;                
                }
                
                $amount = (integer)$amount;
                if ($amount != $item->amount) {
                    $this->_updateBasketItem($user, $item->productId, $amount);
                }
            }
        }
        $this->_helper->redirector->goto('items-list', 'user-basket');
    }
}

